package com.xuelang.pipeline.app.log.config;

import com.xuelang.pipeline.app.log.handler.LogWebSocketHandler;
import com.xuelang.pipeline.app.log.interceptor.LogWebSocketInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;

/**
 * <p>WebSocket配置类</p>
 *
 * @author : yixin.lys
 * @date : 2024-07-01 10:27
 **/
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(logWebSocketHandler(), "/appLog-stream")
                .addInterceptors(logWebSocketInterceptor())
                .setAllowedOrigins("*");
        registry.addHandler(logWebSocketHandler(), "/taskLog-stream")
                .addInterceptors(logWebSocketInterceptor())
                .setAllowedOrigins("*");
        registry.addHandler(logWebSocketHandler(), "/sockjs/log-stream")
                .addInterceptors(logWebSocketInterceptor())
                .setAllowedOrigins("*")
                .withSockJS()
                .setTaskScheduler(taskScheduler());
    }

    @Bean
    public LogWebSocketInterceptor logWebSocketInterceptor(){
        return new LogWebSocketInterceptor();
    }

    @Bean
    public ThreadPoolTaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(10);
        taskScheduler.setThreadNamePrefix("SockJsTaskScheduler-");
        return taskScheduler;
    }

    @Bean
    public LogWebSocketHandler logWebSocketHandler(){
        return new LogWebSocketHandler();
    }

    /**
     * 服务器配置
     * @return
     */
    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer(){
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        container.setMaxTextMessageBufferSize(8192);
        container.setMaxBinaryMessageBufferSize(8192);
        return container;
    }
}
